<template>
  <div>
    <el-dialog :title="isEdit ? '修改部门信息' : '新增子部门'" :visible="isShow" @close="closeDialog" @open="openDialog">
      <el-form ref="formRef" :model="formData" :rules="dataRules">
        <el-form-item label="部门名称" :label-width="'120px'" prop="name">
          <el-input v-model="formData.name" placeholder="2-10个字符" />
        </el-form-item>
        <el-form-item label="部门编码" :label-width="'120px'" prop="code">
          <el-input v-model="formData.code" placeholder="2-10个字符" />
        </el-form-item>
        <el-form-item label="部门负责人" :label-width="'120px'" prop="managerId">
          <el-select v-model="formData.managerId" placeholder="请选择负责人">
            <el-option v-for="item in managerList" :key="item.id" :label="item.username" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" :label-width="'120px'" prop="introduce">
          <el-input v-model="formData.introduce" type="textarea" placeholder="1-100个字符" />
        </el-form-item>
        <el-form-item :label-width="'120px'">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="resetForm">重 置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { usrSimpleRequest } from '@/api/department'
import { addDepartmentRequest, updateDepartmentRequest, getDepartmentDetailRequest } from '@/api/department'
import { cloneDeep } from 'lodash'
export default {
  name: 'AddEditDialog',
  props: {
    'isShow': {
      type: Boolean,
      default: false
    },
    'departmentList': {
      type: Array,
      default: () => []
    },
    'currentId': {
      type: [String, Number],
      default: ''
    },
    'isEdit': {
      type: Boolean,
      default: false
    }
  },
  data() {
    // 部门名业务校验
    const validateDepartmentName = (rule, value, callback) => {
      let newArr = cloneDeep(this.departmentList)
      // 如果是点击的编辑,就将自己筛除
      if (this.isEdit) {
        newArr = newArr.filter(item => item.name !== value)
      }
      // 再进行校验
      if (newArr.some(item => item.name === value)) callback(new Error('部门已存在'))
      else callback()
    }
    // 部门编码业务校验
    const validateDepartmentCode = (rule, value, callback) => {
      let newArr = cloneDeep(this.departmentList)
      if (this.isEdit) {
        newArr = newArr.filter(item => item.code !== value)
      }
      if (newArr.some(item => value === item.code)) callback(new Error('部门编码已存在'))
      else callback()
    }
    return {
      formData: {
        code: '', // 部门编码
        introduce: '', // 部门介绍
        managerId: '', // 部门负责人
        name: '' // 部门名称
      },
      dataRules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 2, max: 10, message: '名称必须2-10个字符', trigger: 'blur' },
          {
            'validator': validateDepartmentName, trigger: ['blur', 'change']
          }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 2, max: 10, message: '编码必须2-10个字符', blur },
          {
            'validator': validateDepartmentCode, trigger: 'blur'
          }
        ],
        managerId: [
          { required: true, message: '请选择负责人', trigger: 'change' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 100, message: '介绍必须1-100个字符', trigger: 'blur' }
        ]
      },
      managerList: []
    }
  },
  // 侦听属性写法
  /* watch: {
    async isEdit(newVal, oldNav) {
      if (newVal) {
        const res = await getDepartmentDetailRequest(this.currentId)
        const { code, introduce, managerId, name } = res.data
        this.formData = {
          code, // 部门编码
          introduce, // 部门介绍
          managerId, // 部门负责人
          name // 部门名称
        }
      }
    }
  }, */
  created() {
    this.getUserSimple()
  },
  methods: {
    // 获取部门负责人列表
    async getUserSimple() {
      try {
        const res = await usrSimpleRequest()
        this.managerList = res.data
      } catch (error) {
        //
      }
    },
    // 打开时判断是否为编辑(使用dialog的open方法)
    async openDialog() {
      if (this.isEdit) {
        // 回显
        const res = await getDepartmentDetailRequest(this.currentId)
        const { code, introduce, managerId, name } = res.data
        this.formData = {
          code, // 部门编码
          introduce, // 部门介绍
          managerId, // 部门负责人
          name // 部门名称
        }
      }
    },

    // 关闭弹窗
    closeDialog() {
      // 子通知者父
      this.$emit('update:isShow', false)
      this.resetForm()
    },
    // 表单校验并修改密码
    submitForm() {
      this.$refs.formRef.validate(async valid => {
        if (valid) {
          try {
            // 判断是修改还是新增
            if (!this.isEdit) { // 新增
              // 发请求
              await addDepartmentRequest({ ...this.formData, pid: this.currentId })
              // 提示
              this.$message.success('添加成功')
            } else { // 修改
              await updateDepartmentRequest({ ...this.formData, id: this.currentId })
              // 提示
              this.$message.success('修改成功')
            }
            // 关闭弹窗
            this.closeDialog()
            // 刷新父组件数据
            this.$emit('update-list')
          } catch (error) {
            //
          }
        }
      })
    },
    // 重置表单
    resetForm() {
      this.$refs.formRef.resetFields()
    }
  }
}
</script>

<style>

</style>
